import { Logger } from "../../../engine/Logger";
import Singleton from "../../../engine/Singleton";
import { JhaoProto } from "./jhaoproto";

export class ProtoManager extends Singleton<ProtoManager>() {

    public init(){
        Logger.log("ProtoManager.init=", JhaoProto)
    }

    encode(proto_ctor, data): Uint8Array {
        if (!data) {
            return null;
        }
        try {
            let buffer_data = proto_ctor.encode(proto_ctor.create(data)).finish();
            return buffer_data;
        } catch (error) {
            Logger.error('encode fail protoName:' + proto_ctor.name + ' data:' + JSON.stringify(data));
            return null
        }
    }


    decode(proto_ctor, data: Uint8Array) {
        if (!data) {
            return null;
        }
        try {
            return proto_ctor.decode(data);
        } catch (error) {
            Logger.error('dncode fail protoName:' + proto_ctor.name);
            return null;
        }
    }

}

export interface WsSendData {
    cmd_index: JhaoProto.CmdIndex,
    en_proto_ctor: any;
    data: any;
    callback?: Function;
}